<template>
  <div class="editProfile">
    <div v-title data-title='个人信息'></div>
    <!-- 头部 -->
    <myheader title="个人信息编辑">
      <template #left>
        <van-icon name="arrow-left" @click="$router.go(-1)" />
      </template>
       <template #right>
        <van-icon name="wap-home-o"
                  @click="$router.push({name:'index'})" />
      </template>
    </myheader>
    <!-- 编辑头像 -->
    <div class="userImg">
      <!-- <img src="../assets/logo.png" alt="" />-->
      <img :src="userinfo.head_img" alt="" />
      <!-- 引入组件要组件中的v-bind v-on v-model的属性 -->
      <van-uploader :after-read="afterRead" />
    </div>
    <!-- 编辑名称,密码 性别 -->
    <mycell @click.native="nickshow=true;nickname=userinfo.nickname">
      <template #title> 名称 </template>
      <template #desc> {{ userinfo.nickname }} </template>
    </mycell>
  <van-dialog v-model="nickshow"
                title="编辑名称"
                show-cancel-button
                @confirm='updateNickname'>
      <van-field v-model.trim="nickname"
                 label="名称"
                 placeholder="请输入手机号" />
    </van-dialog>

    <mycell @click.native="passwordshow=true;newpassword= oraginPassword=''">
      <template #title> 密码 </template>
      <template #desc> ****** </template>
    </mycell>
     <van-dialog v-model="passwordshow"
                title="编辑密码"
                show-cancel-button
                @confirm='updatePassword'
                :beforeClose='beforeClose'
                >
                <!--  :beforeClose='beforeClose' -->
      <van-field v-model.trim="oraginPassword"
                 label="原密码"
                 placeholder="请输入原密码" />
       <van-field v-model.trim="newpassword"
                 label="新密码"
                 placeholder="请输入新密码" />           
    </van-dialog>

    <mycell @click.native="gendershow=true">
      <template #title> 性别 </template>
      <template #desc> {{ userinfo.gender == 1 ? "男" : "女" }} </template>
    </mycell>
    <van-action-sheet 
     v-model="gendershow"
     :actions="actions" 
     @select="onSelect" 
     :close-on-click-action='true'/>
     <!-- 默认情况下点击选项时不会自动收起
     可以通过 close-on-click-action 属性开启自动收起 -->
  </div>
</template>

<script>
import myheader from "@/components/myheader";
import mycell from "@/components/mycell";
import { getUserInfo, editUserInfo } from "@/apis/user";
import axios from "@/utils/request";
import { fileUpload } from "@/apis/fileUpload";
export default {
  data() {
    return {
      // userinfo是个对象
      userinfo: "",
      nickshow:false,
      passwordshow:false,
      gendershow:false,
      nickname:'',
      oraginPassword:'',
      newpassword:'',
      actions: [{ name: '男' }, { name: '女' }]
    };
  },
  components: {
    myheader,
    mycell,
  },
  mounted() {
    getUserInfo(this.$route.params.id).then((res) => {
      this.userinfo = res.data.data;
      this.userinfo.head_img = axios.defaults.baseURL + this.userinfo.head_img;

      // 密码验证,拿来看 
      console.log(this.userinfo);
    });
  },
  methods: {
    // 编辑性别
    onSelect(item){
      // console.log(item);
      // item 返回的是你选择的actions其中对象 
      let current = item.name =='男' ? 1:0;
      editUserInfo(this.userinfo.id,{gender:current})
        .then(res =>{
            if(res.data.message == '修改成功'){
              this.$toast.success("修改成功");
              // 为了下次性别更新
              this.userinfo.gender = current
            }
        })

    },
    // 阻止密码对话框的关闭
    beforeClose (action, done) {
      if (action == 'confirm') {
        // 什么 时候才会阻止关闭： 原密码输入不正确   新密码输入不合法
        if (this. oraginPassword !== this.userinfo.password || !(/^.{3,16}$/.test(this.newpassword))) {
          done(false)
        } else {
          done()
        }
      } else {
        done()
      }
    },
     // 编辑用户昵称
     updateNickname () {
      if (this.nickname.length == 0) {
        this.$toast.fail('编辑失败，请输入昵称')
        return
      }
      editUserInfo(this.userinfo.id, { nickname: this.nickname })
        .then(res => {
          // console.log(res)
          if (res.data.message == "修改成功") {
            // 实现页面效果的刷新：所谓页面刷新是指 将元素所绑定的数据更新
            this.userinfo.nickname = this.nickname
            this.$toast.success("修改成功")
          }
        })
    },
    updatePassword(){
      // 1.先验证原密码正确还是错误 正确就进行新密码验证 错误则返回错误
      // 2.验证新密码输入是否合法
      // 3.原密码新密码
      if(this.oraginPassword == this.userinfo.password){
        if(/^.{3,16}$/.test(this.newpassword)){
          editUserInfo(this.userinfo.id,{password:this.newpassword})
          .then(res=>{
            if(res.data.message == '修改成功'){
              this.$toast.success("修改成功");
              // 为了下次密码更新
              this.userinfo.password = this.newpassword
            }
          })
        }else{
          this.$toast.fail('新密码输入不合法,请输入3-16位密码')
        }
      }else{
        this.$toast.fail('原密码错误')
      }
    },
    afterRead(file) {
      //  此时可以自行将文件上传至服务器
      // console.log(file);
      let formdata = new FormData();

      formdata.append("file", file.file);
      // 1调用方法实现文件上传
      fileUpload(formdata).then((res) => {
        // this.userinfo.head_img =
        //   axios.defaults.baseURL + this.userinfo.head_img;
        this.userinfo.head_img = axios.defaults.baseURL + res.data.data.url;
        console.log(res);

        //2 再次调用方法实现用户信息的编辑
        editUserInfo(this.userinfo.id, { head_img: res.data.data.url }).then(
          (res) => {
            console.log(res);
            if (res.data.message == "修改成功") {
              this.$toast.success("修改成功");
            }
          }
        );
      });
    },
  },
};
</script>

<style lang="less" scoped>
.userImg {
  width: 100%;
  padding: 20px 0;
  display: flex;
  justify-content: center;
  position: relative;
  > img {
    width: 100px;
    height: 100px;
  }
  .van-uploader {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    opacity: 0;

    /deep/ .van-uploader__upload {
      width: 100px;
      height: 100px;
    }
  }
}
</style>